<template>
    <div class="header">
            <span class="logo">米阳光小区物业管理系统</span>
            <div class="avatar">
                <el-avatar :src="user.avatar" size="large" style=" margin-top: 3px;"></el-avatar>
                <el-dropdown  style="top: -3px">
                    <span class="name" style=" margin-right: 5px; color: #fff;  font-size: 20px;">{{user.username}}</span>
                    <el-dropdown-menu slot="dropdown">
                        <el-button @click="updateDrawer()" type="primary" style="background-color:#fff; color: rgb(96, 98, 102); border: none;">
                            个人信息
                        </el-button>
                        <el-dropdown-item><span @click="logout()">退出登录</span></el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
              
            <el-drawer
                title="个人信息"
                :visible.sync="drawer"
                :with-header="false">
                <div class="userInfo">
                    <h3>个人资料详情</h3>
                    <h4>头像</h4>
                    <div class="userAvatar">
                        <el-avatar :src="user.avatar" :size="120" style=" margin-top: 3px;"></el-avatar>
                        <div class="remark">此图片将作为你在本网站上的用户头像显示在各个页面上</div>
                        <button @click="selectImage">更换头像</button>
                        <!-- 隐藏的文件选择输入框 -->
                        <input type="file" ref="fileInput" @change="handleFileChange" style="display: none" accept="image/*" />
                    </div>
   
                    <h4>用户名</h4>
                    <el-input style="top:-30px;" v-model="username" placeholder="请输入内容"></el-input>
                    <h4 style="margin-top:-40px;">性别</h4>
                    <div style="margin-top:-30px;">
                        <el-radio v-model="user.sex" label="1" border>男</el-radio>
                        <el-radio v-model="user.sex" label="0" border>女</el-radio>
                    </div>
                    <el-divider></el-divider>
                    <h4 style="margin-top:-30px;">密码</h4>
                    <div class="password">
                        <el-input style="top:-20px; width: 200px;" :disabled="disabled" placeholder="请输入密码" v-model="password" type="password" show-password></el-input>
                        <button @click="updatePassword()">{{uPContent}}</button>
                    </div>
                    <button class="update" @click="updateUserInfo()">保存更改</button>
                </div>
            </el-drawer>
    </div>
</template>

<script>
import api from '@/api'
import { mapState,mapMutations } from "vuex"
import { cloneDeep } from 'lodash'; // 引入 lodash 的深拷贝方法
export default {
    data() {
        return {
          activeIndex: "/",
          drawer: false,
          password:"123456789",
          disabled:true,
          username: "",
          uPContent:"更换密码",
        };
      },
    computed:{
      ...mapState("login",["user"])
    },
    methods: {
        ...mapMutations("login",["setUser","setUserNull"]),
        updateDrawer(){
            this.drawer = true;
            this.username = cloneDeep(this.user.username);
        },
        logout(){
            api.logout().then(res =>{
                    if(res.type === 'error'){
                        this.$message.error(res.message)
                    }else if(res.data.code === 200){
                        this.setUserNull()
                        localStorage.removeItem("property")
                        localStorage.removeItem("ctumb")
                        this.$message({
                            message: "退出成功",
                            type: 'success'
                        });
                    }else{
                        this.$message.error(res.data.message)
                    }
            })
            this.$router.push("/login")
        },
        updatePassword(){
            this.disabled = !this.disabled;
            this.uPContent = this.uPContent === '更换密码' ? "取消更改" : "更换密码";
            this.password = this.uPContent === '更换密码' ? "123456789" : "";
        },

        // 触发文件选择
        selectImage() {
            // 手动触发文件选择框
            this.$refs.fileInput.click();
        },
        
        // 处理文件变化(更改头像)
        handleFileChange(event) {
            const file = event.target.files[0]; // 获取选择的文件

            // 确保文件是图片
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                
                //将文件上传到后端
                api.uploadFile(file).then(res =>{
                    if(res.type === 'error'){
                        this.$message.error(res.message)
                    }else if(res.data.code === 200){
                        this.user.avatar = res.data.data.url;
                        this.$message({
                            message: res.data.message,
                            type: 'success'
                        });
                    }else{
                        this.$message.error(res.data.message)
                    }
                })
                reader.readAsDataURL(file);
            } else {
                alert('请选择图片文件');
            }
        },
        // 更改用户信息
        updateUserInfo(){
            //参数检验
            if(this.username === ''){
                this.$message.error("昵称不能为空")
                return
            }else if(this.username.length < 3 || this.username.length > 20){
                this.$message.error("用户名格式错误（小于3大于20）")
                return;
            }else{
                this.user.username = this.username;
            }

            const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
            if(this.uPContent === '取消更改' && this.password === ''){
                this.$message.error("密码不能为空")
                return
            }else if(this.uPContent === '取消更改' && !regex.test(this.password)){
                this.$message.error("密码太简单，请确保包含大小写字母、数字和特殊字符，长度至少为 8 位")
                return
            }else{
                this.user.password = this.uPContent === '更换密码' ? "" : this.password;
            }

            api.updateUserInfo(this.user).then(res =>{
                    if(res.type === 'error'){
                        this.$message.error(res.message)
                    }else if(res.data.code === 200){
                        this.user.password = ''
                        let property = JSON.parse(localStorage.getItem("property"));
                        property.userInfo = this.user
                        //本地缓存
                        localStorage.setItem(
                            "property",
                            JSON.stringify(property)
                        );                     
                        this.drawer = false
                        this.$message({
                            message: res.data.message,
                            type: 'success'
                        });
                    }else{
                        this.$message.error(res.data.message)
                    }
            })
        }
    }
}
</script>

<style scoped lang="less">
.header {
    height: 70px;
    background-color: rgb(83,174,229);
    line-height: 70px;
    border-bottom: 1px solid  rgb(243,243,243);
    .logo{
        height: 50px;
        font-size: 25px;
        margin-left: 20px;
        color: #fff;
    }
    .avatar{
        float: right;
        right: 10px;
        height: 50px;   
        color: black;
        margin-top: 3px;
        .el-avatar {
            top: 10px;
            transform: translate(10%, 22%);
            margin-right: 20px;
        };
        .name{
            margin-top: -1px;
            height: 50px;
            padding-right: 20px;
            color: #fff;
            font-size: 20px;
        }
    }
    .userInfo{
        margin: 20px;
    }
    .userInfo .userAvatar .el-avatar{
        position: relative;
    }
    .userInfo .userAvatar .remark{
        position: absolute;
        top: 175px;
        left: 150px;
        height: 50px;
        line-height: 20px;
        color: rgb(153, 153, 160);
    }
    .userInfo .userAvatar button{
        position: absolute;
        width: 87px;
        height: 35px;
        top: 225px;
        left: 150px;
        background-color: rgb(250, 250, 250);
        color: rgb(3, 3, 4);
        border: 1px solid  rgb(243,243,243);
    }
    .userInfo .password button{
        float: right;
        width: 87px;
        height: 35px;
        background-color: rgb(250, 250, 250);
        color: rgb(3, 3, 4);
        border: 1px solid  rgb(243,243,243);
    }
    .userInfo .update{
        width: 100%;
        height: 35px;
        background-color: rgb(3, 3, 4);
        color: #fff;
        border: 1px solid  rgb(243,243,243);
    }
}
</style>